/**
 * 目录树管理器 - 提取markdown标题并生成导航
 */
class TOCManager {
    constructor() {
        this.tocContainer = null;
        this.currentHeadings = [];
        this.isVisible = false;
        this.init();
    }

    init() {
        this.createTOCContainer();
        this.bindEvents();
        this.bindEditorEvents();
    }

    createTOCContainer() {
        // 创建目录容器
        const tocPanel = document.createElement('div');
        tocPanel.id = 'toc-panel';
        tocPanel.className = 'toc-panel';
        tocPanel.innerHTML = `
            <div class="toc-header">
                <h3>目录</h3>
                <button id="toc-toggle" class="btn btn-icon" title="切换目录显示">📋</button>
                <button id="toc-close" class="btn btn-icon" title="关闭目录">✕</button>
            </div>
            <div class="toc-content">
                <div id="toc-list" class="toc-list">
                    <div class="toc-empty">暂无标题</div>
                </div>
            </div>
        `;

        // 添加到主内容区域
        const mainContent = document.querySelector('.main-content');
        if (mainContent) {
            mainContent.appendChild(tocPanel);
            this.tocContainer = tocPanel;
        }

        // 创建工具栏按钮
        this.createToolbarButton();
    }

    createToolbarButton() {
        const toolbar = document.querySelector('.toolbar-right');
        if (toolbar) {
            const tocBtn = document.createElement('button');
            tocBtn.id = 'show-toc';
            tocBtn.className = 'btn btn-icon';
            tocBtn.title = '显示目录';
            tocBtn.innerHTML = '📋';
            
            // 插入到设置按钮之前
            const settingsBtn = document.getElementById('settings');
            if (settingsBtn) {
                toolbar.insertBefore(tocBtn, settingsBtn);
            } else {
                toolbar.appendChild(tocBtn);
            }
        }
    }

    bindEvents() {
        // 显示目录按钮
        document.getElementById('show-toc')?.addEventListener('click', () => {
            this.showTOC();
        });

        // 关闭目录按钮
        document.getElementById('toc-close')?.addEventListener('click', () => {
            this.hideTOC();
        });

        // 切换目录显示按钮
        document.getElementById('toc-toggle')?.addEventListener('click', () => {
            this.toggleTOC();
        });

        // 点击目录项跳转
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('toc-item')) {
                const headingId = e.target.dataset.headingId;
                this.scrollToHeading(headingId);
            }
        });

        // 监听窗口大小变化
        window.addEventListener('resize', () => {
            this.adjustLayout();
        });
    }

    bindEditorEvents() {
        // 监听编辑器内容变化
        document.addEventListener('editorContentChanged', () => {
            this.updateTOC();
        });

        // 如果编辑器已经存在，立即更新目录
        if (window.editor) {
            this.updateTOC();
        }

        // 监听编辑器初始化
        document.addEventListener('editorInitialized', () => {
            this.updateTOC();
        });
    }

    updateTOC() {
        const content = this.getEditorContent();
        if (!content) return;

        const headings = this.extractHeadings(content);
        this.currentHeadings = headings;
        this.renderTOC(headings);
    }

    getEditorContent() {
        if (window.editor && window.editor.getValue) {
            return window.editor.getValue();
        }
        
        // 备用方案：从textarea获取
        const textarea = document.querySelector('#editor textarea');
        if (textarea) {
            return textarea.value;
        }
        
        return '';
    }

    extractHeadings(content) {
        const lines = content.split('\n');
        const headings = [];
        let headingId = 0;

        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            const match = line.match(/^(#{1,6})\s+(.+)$/);
            
            if (match) {
                const level = match[1].length;
                const text = match[2].trim();
                const id = `heading-${++headingId}`;
                
                headings.push({
                    id: id,
                    level: level,
                    text: text,
                    line: i + 1,
                    anchor: this.generateAnchor(text)
                });
            }
        }

        return headings;
    }

    generateAnchor(text) {
        return text
            .toLowerCase()
            .replace(/[^\w\u4e00-\u9fff\s-]/g, '') // 保留中文、英文、数字、空格、连字符
            .replace(/\s+/g, '-')
            .replace(/-+/g, '-')
            .replace(/^-|-$/g, '');
    }

    renderTOC(headings) {
        const tocList = document.getElementById('toc-list');
        if (!tocList) return;

        if (headings.length === 0) {
            tocList.innerHTML = '<div class="toc-empty">暂无标题</div>';
            return;
        }

        const tocHTML = headings.map(heading => {
            const indent = (heading.level - 1) * 16;
            return `
                <div class="toc-item" 
                     data-heading-id="${heading.id}" 
                     data-level="${heading.level}"
                     data-line="${heading.line}"
                     style="padding-left: ${indent}px;"
                     title="第 ${heading.line} 行">
                    <span class="toc-text">${this.escapeHtml(heading.text)}</span>
                    <span class="toc-line">L${heading.line}</span>
                </div>
            `;
        }).join('');

        tocList.innerHTML = tocHTML;
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    scrollToHeading(headingId) {
        const heading = this.currentHeadings.find(h => h.id === headingId);
        if (!heading) return;

        // 如果编辑器支持跳转到行
        if (window.editor && window.editor.gotoLine) {
            window.editor.gotoLine(heading.line);
            window.editor.focus();
        } else if (window.editor && window.editor.setCursor) {
            // CodeMirror风格的API
            window.editor.setCursor(heading.line - 1, 0);
            window.editor.focus();
        } else {
            // 备用方案：滚动到预览区域对应位置
            this.scrollToPreviewHeading(heading.anchor);
        }

        // 高亮当前目录项
        this.highlightTOCItem(headingId);
    }

    scrollToPreviewHeading(anchor) {
        const preview = document.getElementById('preview');
        if (!preview) return;

        // 查找对应的标题元素
        const headingElement = preview.querySelector(`[id="${anchor}"], h1, h2, h3, h4, h5, h6`);
        if (headingElement) {
            headingElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
    }

    highlightTOCItem(headingId) {
        // 移除之前的高亮
        document.querySelectorAll('.toc-item.active').forEach(item => {
            item.classList.remove('active');
        });

        // 添加新的高亮
        const tocItem = document.querySelector(`[data-heading-id="${headingId}"]`);
        if (tocItem) {
            tocItem.classList.add('active');
        }
    }

    showTOC() {
        if (this.tocContainer) {
            this.tocContainer.classList.add('visible');
            this.isVisible = true;
            this.adjustLayout();
            this.updateTOC(); // 显示时更新目录
        }
    }

    hideTOC() {
        if (this.tocContainer) {
            this.tocContainer.classList.remove('visible');
            this.isVisible = false;
            this.adjustLayout();
        }
    }

    toggleTOC() {
        if (this.isVisible) {
            this.hideTOC();
        } else {
            this.showTOC();
        }
    }

    adjustLayout() {
        const mainContent = document.querySelector('.main-content');
        const editorContainer = document.querySelector('.editor-container');
        
        if (mainContent && editorContainer) {
            if (this.isVisible) {
                mainContent.classList.add('toc-visible');
            } else {
                mainContent.classList.remove('toc-visible');
            }
        }
    }

    // 获取当前目录数据（供其他模块使用）
    getCurrentTOC() {
        return this.currentHeadings;
    }

    // 刷新目录
    refresh() {
        this.updateTOC();
    }
}

// 初始化目录管理器
window.tocManager = new TOCManager();